package cc.fine.svc.main.service.impl.rel;

import cc.fine.svc.main.bean.es.VideoEsEntity;
import cc.fine.svc.main.bean.po.RelVideoTag;
import cc.fine.svc.main.bean.po.TblTag;
import cc.fine.svc.main.mapper.RelVideoTagMapper;
import cc.fine.svc.main.service.rel.RelVideoTagService;
import cc.fine.svc.main.service.tbl.TblTagService;
import cc.fine.svc.main.service.tbl.TblVideoService;
import cc.fine.svc.main.utils.EsUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wyihe
 * @since 2023-10-25
 */
@Service
public class RelVideoTagServiceImpl extends ServiceImpl<RelVideoTagMapper, RelVideoTag> implements RelVideoTagService {


    @Autowired
    private EsUtil esUtil;

    @Autowired
    private TblTagService tagService;

    @Override
    public List<TblTag> tages(String videoId) {

        List<TblTag> res = baseMapper.tags(videoId);
        if (res == null) res = new ArrayList<>();
        return res;

    }

    @Override
    public void rel(String videoId, String tagId) {
        // 已经存在就不要添加了
        QueryWrapper<RelVideoTag> w1 = new QueryWrapper<>();
        w1.eq("video_id", videoId);
        w1.eq("tag_id", tagId);
        if (!list(w1).isEmpty()) {
            return;
        }

        RelVideoTag relVideoTag = new RelVideoTag();
        relVideoTag.setTagId(tagId);
        relVideoTag.setVideoId(videoId);
        String id = UUID.randomUUID().toString();
        relVideoTag.setId(id);
        save(relVideoTag);

        // 存入es
        List<TblTag> tags = tagService.getTags(videoId);
        tags.add(tagService.getById(tagId));

        String tagStr = tags.stream()
                .map(x -> x.getTitle())
                .collect(Collectors.toList()).toString();

        VideoEsEntity entity = new VideoEsEntity();
        entity.setTagStr(tagStr);
        try {
            esUtil.updateDataById(entity, TblVideoService.Es_Index, videoId);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> videoIds(String tagId) {
        QueryWrapper<RelVideoTag> w =  new QueryWrapper<>();
        w.eq("tag_id", tagId);
        return list(w).stream()
                .map(x -> x.getVideoId())
                .collect(Collectors.toList());
    }
}
